package com.ssl.basics.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 描述：
 *
 * @author ssl
 * @create 2021/7/5 0005.
 */
@Slf4j
public class FutureTaskTest {


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        log.info("开始执行");

        Callable<Integer> callable1 = () -> {
            Thread.sleep(5000);
            int a = 3 / 0;
            return 1;
        };

        FutureTask<Integer> futureTask1 = new FutureTask<>(callable1);

        log.info("futureTask1 start");
        new Thread(futureTask1, "t1").start();
        log.info("futureTask1 end");

        Callable<Integer> callable2 = () -> {
            Thread.sleep(6000);
            return 2;
        };

        FutureTask<Integer> futureTask2 = new FutureTask<>(callable2);

        log.info("futureTask2 start");
        new Thread(futureTask2, "t2").start();
        log.info("futureTask2 end");

        // Future.get的行为取决于任务的状态.如果任务已经完成,那么get会立即返回结果,
        // 否则get将阻塞直到任务进入完成状态,然后返回结果或者抛出异常
       System.out.println(futureTask1.get()+futureTask2.get());
       log.info("结束计算");
    }
}
